<!--
 * @Description: 
 * @Autor: codeBo
 * @Date: 2025-05-13 15:07:52
 * @LastEditors: lihaibo@shanshu.ai
 * @LastEditTime: 2025-05-16 13:19:33
-->
<script setup>
import { Panel, useVueFlow } from '@vue-flow/core'
import useDeviceFlowStore from '../pinia.ts'
const flowStore = useDeviceFlowStore()
const isEdit = computed(() => flowStore.isEdit)
import { useScreenshot } from '../hook/useScreenshot'

const props = defineProps(['addNodeHandler', 'addTextHandler'])
const {
  setNodes,
  setState,
  nodes,
  addNodes,
  dimensions,
  toObject,
  fromObject,
  vueFlowRef,
  fitView,
  getNodes
} = useVueFlow()
const { capture } = useScreenshot()
function onSave() {}

function saveHandler() {
  flowStore.saveNodeHandler(toObject().nodes)
}

// 新增事件 text 文本  rect 矩形

const addNodesHandler = (type) => {
  const nodeConfig = {
    text: {
      type: 'inputnode',
      data: { label: 'text' },
      zIndex: 4
    },
    rect: {
      type: 'resizable',
      data: { label: 'rect' },
      style: { width: '380px', height: '140px' },
      zIndex: 3
    }
  }
  const config = nodeConfig[type]
  if (config) {
    addNodes({
      id: Date.now(), // 随机生成一个id， 这个id没有数据意义，只用来显示框及文字。 和后端存储的原始数据不影响，所以不需要后端指定id
      position: { x: -10, y: -60 },
      ...config
    })
    fitView({
      padding: 0.2, // 控制边距比例，防止缩得太小
      nodes: [getNodes.value[0].id], // 不指定具体节点则自动计算全部节点
      duration: 500, // 动画时间
      maxZoom: 1.5,
      minZoom: 0.5
    })
  } else {
    console.warn(`Unknown node type: ${type}`)
  }
}
const cancelHandler = () => {
  setState({ nodes: JSON.parse(flowStore.initNodes) })
  flowStore.closeEdit()
}
const resetHandler = () => {
  setState({ nodes: flowStore.nodes })
}
const doScreenshot = () => {
  if (!vueFlowRef.value) {
    console.warn('VueFlow element not found')
    return
  }
  capture(vueFlowRef.value, { shouldDownload: true })
}
</script>

<template>
  <Panel position="top-right">
    <div class="buttons">
      <el-button v-if="!isEdit" @click="flowStore.openEdit">修改</el-button>
      <el-button v-if="!isEdit" @click="flowStore.resetData">重置</el-button>
      <el-button v-if="isEdit" @click="addNodesHandler('rect')">新增矩形</el-button>
      <el-button v-if="isEdit" @click="addNodesHandler('text')">新增文字</el-button>
      <el-button v-if="isEdit" @click="saveHandler">保存</el-button>
      <!-- <el-button v-if="isEdit" @click="resetHandler">重置</el-button> -->
      <el-button v-if="isEdit" @click="cancelHandler">取消编辑</el-button>
      <!-- <el-button v-if="!isEdit" @click="doScreenshot">导出图片</el-button> -->
    </div>
  </Panel>
</template>
<style lang="scss" scoped>
.buttons {
  > button {
    color: rgba(#082050, 0.7);
    border-color: #c9d2e4;
  }
}
</style>
